﻿using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Dyn.News.Models;
using Dyn.News.Routing;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.Core.Routable.Models;
using Dyn.News.Extensions;
using Dyn.Media.Services;
using Orchard;
using Orchard.Data;
using Dyn.Media.Models;
using Dyn.Media.ViewModels;
using Dyn.News.ViewModels;
using Orchard.Core.Common.Models;
using System.Web;

namespace Dyn.News.Services {
    [UsedImplicitly]
    public class Categoryervice : ICategoryervice {
        private readonly IContentManager _contentManager;
        private readonly ICategoryPathConstraint _categoryPathConstraint;
        private readonly IMediaListService _mediaListService;
        private readonly IRepository<NewsContentCategoryMenuWidgetRecord> _categoryMenuWidget;
        private readonly IRepository<NewsContentCategoryWidgetRecord> _categoryWidget;
        //private readonly IRepository<NewsContentProduct_CategoryRecord> _categoryProduct;

        //public Categoryervice(IMediaListService mediaListService, IOrchardServices service,
        //    IRepository<NewsContentCategoryMenuWidgetRecord> categoryMenuWidget,
        //    IRepository<NewsContentCategoryWidgetRecord> categoryWidget)
        //{
        //    //_categoryProduct = categoryProduct;
        //    _categoryWidget = categoryWidget;
        //    _categoryMenuWidget = categoryMenuWidget;
        //    _service = service;
        //    _mediaListService = mediaListService;
        //}
        public Categoryervice(IContentManager contentManager, ICategoryPathConstraint categoryPathConstraint, IMediaListService mediaListService, IRepository<NewsContentCategoryMenuWidgetRecord> categoryMenuWidget,
            IRepository<NewsContentCategoryWidgetRecord> categoryWidget)
        {
            _contentManager = contentManager;
            _categoryPathConstraint = categoryPathConstraint;
            _categoryWidget = categoryWidget;
            _categoryMenuWidget = categoryMenuWidget;
            _mediaListService = mediaListService;
        
        }

        public NewsCategoryPart Get(string path) {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>()
                .Join<RoutePartRecord>().Where(rr => rr.Path == path)
                .List().FirstOrDefault();
        }

        public ContentItem Get(int id, VersionOptions versionOptions) {
            return _contentManager.Get(id, versionOptions);
        }
        public IEnumerable<NewsCategoryPart> AllParent()
        {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>().Where(p=>p.ParentID==Utils.ParentID).OrderBy(br => br.OrderDisplay)
                .Join<RoutePartRecord>().List();
        }
        public IEnumerable<NewsCategoryPart> Get() {
            return Get(VersionOptions.Published);
        }



        public IEnumerable<NewsCategoryPart> Get(VersionOptions versionOptions) {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>(versionOptions)
                .Join<RoutePartRecord>()
                .OrderBy(br => br.Title)
                .List();
        }
        public IEnumerable<NewsCategoryPart> Get(VersionOptions versionOptions,int idParent)
        {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>(versionOptions).Where(p=>p.ParentID==idParent)
                .Join<RoutePartRecord>()
                .OrderBy(br => br.Title)
                .List();
        }

        public NewsCategoryPart GetFromSlug(string slug) {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>()
                .Join<RoutePartRecord>().Where(rr => rr.Slug == slug)
                .List().FirstOrDefault();
        }

        public void Delete(ContentItem category) {
            _contentManager.Remove(category);
            _categoryPathConstraint.RemovePath(category.As<IRoutableAspect>().Path);
        }


       
        public MediaFile GetCurrentMediaFile(NewsCategoryPart part)
        {
            MediaListPart mediaList = part.As<MediaListPart>();
            MediaListViewModel viewModel = new MediaListViewModel();
            MediaFile mediaFileCurrent = new MediaFile();
            if (mediaList != null)
            {
                MediaList mediaFiles = _mediaListService.GetMediaList(mediaList.MediaListName);
                //Lấy ra ảnh đại diện cho category
                if (mediaFiles != null)
                {
                    mediaFileCurrent = mediaFiles.MediaFiles.SingleOrDefault(m => m.Name == mediaList.MediaFileCurentName);
                    if (mediaFileCurrent == null)
                        return mediaFiles.MediaFiles.FirstOrDefault();
                }
            }
            return mediaFileCurrent;
        }


        public IList<ContentCategoryMenuWidgetViewModel> GetCategories(NewsCategoryMenuWidgetPart part)
        {
            var lst = new List<ContentCategoryMenuWidgetViewModel>();
            var root = _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>().Where(p => p.ParentID == 0).OrderBy(p => p.OrderDisplay).List();
            foreach (var item in root)
            {
                var image = GetCurrentMediaFile(item);
                var tmp = new ContentCategoryMenuWidgetViewModel
                {
                    Id = item.Id,
                    Name = item.Name,
                    Parent = null,
                    IsEnable = part.ContentCategoryMenuWidgets.Where(c => c.Id == item.Id).Count() > 0,
                    DisplayOrder = part.ContentCategoryMenuWidgets.Where(c => c.Id == item.Id).Count() > 0
                                ? _categoryMenuWidget.Get(d => d.NewsCategoryPartRecord.Id == item.Id && d.NewsCategoryMenuWidgetPartRecord.Id == part.Id).DisplayOrder
                                : 0,
                    image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
                    CategoryUrl = item.As<RoutePart>().Slug
                };
                lst.Add(tmp);
                AddCategory(tmp, part);
            }
            return lst;
        }
        private void AddCategory(ContentCategoryMenuWidgetViewModel category, NewsCategoryMenuWidgetPart part)
        {
            var childs = _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>().Where(p => p.ParentID == category.Id).OrderBy(p => p.OrderDisplay).List();
            category.Childs = new List<ContentCategoryMenuWidgetViewModel>();
            foreach (var item in childs)
            {
                var image = GetCurrentMediaFile(item);
                var tmp = new ContentCategoryMenuWidgetViewModel
                {
                    Id = item.Id,
                    Name = item.Name,
                    Parent = category,
                    IsEnable = part.ContentCategoryMenuWidgets.Where(c => c.Id == item.Id).Count() > 0,
                    DisplayOrder = part.ContentCategoryMenuWidgets.Where(c => c.Id == item.Id).Count() > 0
                                ? _categoryMenuWidget.Get(d => d.NewsCategoryPartRecord.Id == item.Id && d.NewsCategoryMenuWidgetPartRecord.Id == part.Id).DisplayOrder
                                : 0,
                    image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
                    CategoryUrl = item.As<RoutePart>().Path
                };
                category.Childs.Add(tmp);
                AddCategory(tmp, part);
            }
        }
        public IList<ContentCategoryWidgetViewModel> GetCategoriesWidget(NewsCategoryWidgetPart part)
        {

            var lst = new List<ContentCategoryWidgetViewModel>();
            var root = _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>().Where(p => p.ParentID == 0).OrderBy(p => p.OrderDisplay).List();
            foreach (var item in root)
            {
                var image = GetCurrentMediaFile(item);
                var tmp = new ContentCategoryWidgetViewModel
                {
                    Id = item.Id,
                    CategoryName = item.Name,
                    Parent = null,
                    IsEnable = part.ContentCategoryWidgets.Where(c => c.Id == item.Id).Count() > 0,
                    DisplayOrder = part.ContentCategoryWidgets.Where(c => c.Id == item.Id).Count() > 0
                                ? _categoryWidget.Get(d => d.NewsCategoryPartRecord.Id == item.Id && d.NewsCategoryWidgetPartRecord.Id == part.Id).DisplayOrder
                                : 0,
                    image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
                    CategoryUrl = item.As<RoutePart>().Path
                };
                lst.Add(tmp);
                AddCategoriesWidget(tmp, part);
            }
            return lst;
        }
        private void AddCategoriesWidget(ContentCategoryWidgetViewModel category, NewsCategoryWidgetPart part)
        {
            var childs = _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>().Where(p => p.ParentID == category.Id).OrderBy(p => p.OrderDisplay).List();
            category.Childs = new List<ContentCategoryWidgetViewModel>();
            foreach (var item in childs)
            {
                var image = GetCurrentMediaFile(item);
                var tmp = new ContentCategoryWidgetViewModel
                {
                    Id = item.Id,
                    CategoryName = item.Name,
                    Parent = category,
                    IsEnable = part.ContentCategoryWidgets.Where(c => c.Id == item.Id).Count() > 0,
                    DisplayOrder = part.ContentCategoryWidgets.Where(c => c.Id == item.Id).Count() > 0
                                ? _categoryWidget.Get(d => d.NewsCategoryPartRecord.Id == item.Id && d.NewsCategoryWidgetPartRecord.Id == part.Id).DisplayOrder
                                : 0,
                    image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
                    CategoryUrl = item.As<RoutePart>().Path
                };
                category.Childs.Add(tmp);
                AddCategoriesWidget(tmp, part);
            }
        }
        //public IList<ContentProduct_CategoryViewModel> GetCategories(ProductPart part)
        //{

        //    var lst = new List<ContentProduct_CategoryViewModel>();
        //    var root = _service.ContentManager.Query<ECategoryPart, ECategoryPartRecord>().Where(p => p.ParentCategoryId == null).OrderBy(p => p.DisplayOrder).List();
        //    foreach (var item in root)
        //    {
        //        var image = GetCurrentMediaFile(item);
        //        var tmp = new ContentProduct_CategoryViewModel
        //        {
        //            Id = item.Id,
        //            CategoryName = item.Name,
        //            Parent = null,
        //            IsEnable = part.ContentProducts_Categories.Where(c => c.Id == item.Id).Count() > 0,
        //            DisplayOrder = part.ContentProducts_Categories.Where(c => c.Id == item.Id).Count() > 0
        //                        ? _categoryProduct.Get(d => d.ECategoryPartRecord.Id == item.Id && d.ProductPartRecord.Id == part.Id).DisplayOrder
        //                        : 0,
        //            image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
        //            CategoryUrl = item.As<RoutePart>().Path
        //        };
        //        lst.Add(tmp);
        //        AddCategories(tmp, part);
        //    }
        //    return lst;
        //}
        //private void AddCategories(ContentProduct_CategoryViewModel category, ProductPart part)
        //{
        //    var childs = _service.ContentManager.Query<ECategoryPart, ECategoryPartRecord>().Where(p => p.ParentCategoryId == category.Id).OrderBy(p => p.DisplayOrder).List();
        //    category.Childs = new List<ContentProduct_CategoryViewModel>();
        //    foreach (var item in childs)
        //    {
        //        var image = GetCurrentMediaFile(item);
        //        var tmp = new ContentProduct_CategoryViewModel
        //        {
        //            Id = item.Id,
        //            CategoryName = item.Name,
        //            Parent = category,
        //            IsEnable = part.ContentProducts_Categories.Where(c => c.Id == item.Id).Count() > 0,
        //            DisplayOrder = part.ContentProducts_Categories.Where(c => c.Id == item.Id).Count() > 0
        //                        ? _categoryProduct.Get(d => d.ECategoryPartRecord.Id == item.Id && d.ProductPartRecord.Id == part.Id).DisplayOrder
        //                        : 0,
        //            image = image.PublicUrl != null ? image.Thumbnail.PublicUrl : string.Empty,
        //            CategoryUrl = item.As<RoutePart>().Path
        //        };
        //        category.Childs.Add(tmp);
        //        AddCategories(tmp, part);
        //    }
        //}

        public IEnumerable<NewsCategoryPart> Get(int skip, int count, VersionOptions versionOptions)
        {
            return GetCatalogQuery(versionOptions).Slice(skip, count).Select(p => p.As<NewsCategoryPart>());
        }

        private IContentQuery<ContentItem, CommonPartRecord> GetCatalogQuery(VersionOptions versionOptions)
        {
            return
                _contentManager.Query(versionOptions, "ArticlePart").Join<CommonPartRecord>().OrderByDescending(cr => cr.CreatedUtc);
        }
    }
}